import Taro, { Component } from '@tarojs/taro'
import { View, ScrollView } from '@tarojs/components'
import { AtActivityIndicator, AtLoadMore, AtIcon } from 'taro-ui'
import bg from '@assets/images/2653.mp3'
import PropTypes from 'prop-types'
import classNames from 'classnames'
import './index.scss'

class Pulltopushrefresh extends Component {
  static options = {
    addGlobalClass: true
  }
  static externalClasses = ['custom-class']
  static propTypes = {
    onPullDown: PropTypes.func,
    onLoadMore: PropTypes.func,
    loadState: PropTypes.oneOf(['loading', 'noMore', '']),
    isHidenBottomLoading: PropTypes.bool,
    showScrollTop: PropTypes.bool,
    style: PropTypes.object
  }
  static defaultProps = {
    loadState: '',
    isHidenBottomLoading: false,
    style: {},
    showScrollTop: false,
    onPullDown: () => {},
    onLoadMore: () => {}
  }

  constructor() {
    super(...arguments)
    this.state = {
      downText: '下拉刷新',
      downDragStyle: { height: 0 + 'px' },
      dargStyle: { transform: `translateY(0px)` },
      scrollY: true,
      status: 'loading',
      returnTop: 0,
      transformReturn: false
    }
    this.startP = {}
    this.toTopBol = true
    this.dargState = 0 // 0不做操作 1刷新
    this.isPull = false
    this.isPullMax = false
    this.isShow = false
    this.recordScroll = 0
    this.refreshAudio = Taro.createInnerAudioContext()
    this.refreshAudio.src = bg
    this.refreshAudio.onError(e => {
      console.log(e, 'err')
    })
  }
  componentWillUnmount() {
    this.refreshAudio.destroy()
  }
  playVideo() {
    this.refreshAudio.play()
  }
  touchmove = e => {
    let move_p = e.touches[0], // 移动时的位置
      deviationX = 0.6, // 左右偏移量(超过这个偏移量不执行下拉操作)
      deviationY = 40, // 拉动长度（低于这个值的时候不执行）
      maxY = 80, // 拉动的最大高度
      start_x = this.startP.clientX,
      start_y = this.startP.clientY,
      move_x = move_p.clientX,
      move_y = move_p.clientY,
      dev = Math.abs(move_x - start_x) / Math.abs(move_y - start_y)
    // console.log(dev, 'dev')
    if (dev < deviationX) {
      //   console.log(this.toTopBol)
      // 当偏移数值大于设置的偏移数值时则不执行操作
      if (move_y - start_y > 0 && this.toTopBol) {
        // 下拉操作
        let pY = Math.abs(move_y - start_y) / 6 // 拖动倍率
        // console.log(pY, deviationY)
        if (!this.isPullMax && pY >= deviationY) {
          this.dargState = 1
          this.isPullMax = true
          this.setState({
            downText: '释放刷新'
          })
        } else {
          if (this.isPull) return
          this.dargState = 0
          this.setState({
            downText: '下拉刷新',
            dargStyle: { transform: `translateY(${maxY}px)` },
            downDragStyle: { height: maxY + 'px' },
            scrollY: false
          })
          this.isPull = true
        }
      }
    }
  }

  touchEnd = () => {
    if (this.dargState === 1) {
      this._down()
    } else {
      this.reduction()
    }
  }

  _down = () => {
    const { onPullDown } = this.props
    onPullDown &&
      onPullDown(() => {
        console.log('downFinish')
        this.reduction()
        this.playVideo()
      })
  }

  reduction = () => {
    // 刷新之后重置
    this.setState({
      dargStyle: { transform: `translateY(0px)` },
      downText: '下拉刷新',
      downDragStyle: { height: 0 + 'px' },
      scrollY: true
    })
    this.dargState = 0
    this.isPull = false
    this.isPullMax = false
  }
  toTopScrollClick() {
    this.toTopBol = true
  }
  onScroll(e) {
    const { scrollTop } = e.detail || {}
    this.recordScroll = scrollTop
    if (this.toTopBol && scrollTop > 10) {
      //   console.log(e)
      this.toTopBol = false
    }
    if (this.props.showScrollTop && !this.isShow && scrollTop > 500) {
      this.setState({
        transformReturn: true
      })
      this.isShow = true
    }
    if (this.props.showScrollTop && this.isShow && scrollTop < 500) {
      this.setState({
        transformReturn: false
      })
      this.isShow = false
    }
  }
  touchStart = e => {
    this.startP = e.touches[0]
  }
  // console.log(info)
  loadRecommend = () => {
    this.props.onLoadMore(hasMore => {
      let status = hasMore || 'loading'
      console.log('loading', status)
      this.setState({
        status: status
      })
    })
  }
  clickReturnTop = () => {
    this.setState(
      {
        returnTop: this.recordScroll
      },
      () => {
        this.setState({
          returnTop: 0
        })
      }
    )
    console.log('movable-view')
    return false
  }
  render() {
    const { downDragStyle, downText, dargStyle, scrollY, status, returnTop, transformReturn } = this.state
    const { isHidenBottomLoading, children, style, loadState, showScrollTop } = this.props
    return (
      <View className='pullToPushRefresh custom-class' style={style}>
        <View className='pullToPushRefresh-downDragBox' style={{ ...downDragStyle, transition: 'height 0.5s ease ' }}>
          <AtActivityIndicator content={downText}></AtActivityIndicator>
        </View>
        <ScrollView
          style={{ ...dargStyle, ...style, transition: 'transform 0.5s ease' }}
          className='home__wrap'
          scrollY={scrollY}
          onTouchMove={this.touchmove}
          onTouchEnd={this.touchEnd}
          onTouchStart={this.touchStart}
          onScrollToLower={this.loadRecommend}
          onScrollToUpper={this.toTopScrollClick}
          onScroll={this.onScroll}
          upperThreshold='80'
          scrollTop={returnTop}
          scrollAnchoring
          scrollWithAnimation
        >
          {children}
          {!isHidenBottomLoading && (
            <AtLoadMore
              onClick={this.loadRecommend}
              status={loadState || status}
              className='pullToPushRefresh-loadmore'
              noMoreTextStyle={{ color: '#ccc', display: 'flex', justifyContent: 'center', alignItems: 'center' }}
            />
          )}
        </ScrollView>
        {showScrollTop && (
          <View className={classNames('pullToPushRefresh-return-top', transformReturn && 'show')} onClick={this.clickReturnTop}>
            <AtIcon prefixClass='xt' value='huidaodingbu' size='40' color='rgba(0,0,0,0.6)'></AtIcon>
          </View>
        )}
      </View>
    )
  }
}

export default Pulltopushrefresh
